<?php

namespace addons\aliocr\controller;

use think\addons\Controller;
use think\Config;
use think\Hook;
use addons\aliocr\library\Aliocr;
use app\admin\library\Auth as AdminAuth ;
use app\common\library\Auth as UserAuth;

/**
 * 阿里OCR文字识别
 */
class Index extends Controller
{
    protected $config = [];
    protected $ocr = null;
    protected $isAdminLogined = false;
    protected $isUserLogined = false;

    public function _initialize()
    {
        parent::_initialize();
        $this->config = get_addon_config('aliocr');
        $this->ocr = new Aliocr();

        $this->isAdminLogined = AdminAuth::instance()->isLogin();
        $this->isUserLogined = UserAuth::instance()->isLogin();

        // 该页面是否开放给前台用户使用
        if ($this->config['frontend']) {
            if (!$this->isAdminLogined && !$this->isUserLogined) {
                $this->error('请登录会员后使用!');
            }
        } else {
            if (!$this->isAdminLogined) {
                $this->error('使用该页面需后台登录状态!');
            }
        }
    }

    public function index()
    {
        $lang = strip_tags($this->request->langset());
        $site = Config::get("site");
        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        // 配置信息
        $config = [
            'site'           => array_intersect_key($site, array_flip(['name', 'cdnurl', 'version', 'timezone', 'languages'])),
            'upload'         => $upload,
            'modulename'     => 'addons',
            'controllername' => 'index',
            'actionname'     => $this->request->action(),
            'jsname'         => 'aliocr',
            'moduleurl'      => rtrim(url("/index", '', false), '/'),
            'language'       => $lang
        ];
        $config = array_merge($config, Config::get("view_replace_str"));

        // 配置信息后
        Hook::listen("config_init", $config);

        $this->view->assign('jsconfig', $config);
        $this->view->assign('site', $site);

        $isUploadTips = $upload['cdnurl'] ? false : ($this->isUserLogined ? false : true);
        $this->view->assign('isUploadTips', $isUploadTips);

        $ocrTypeList = array(
            'id_card-face'=> '身份证正面',
            'id_card-back'=> '身份证背面',
            'bank_card'=> '银行卡',
            'vehicle_plate'=> '车牌号',
            'driver_license-face'=> '驾驶证首页',
            'driver_license-back'=> '驾驶证副页',
            'business_license'=> '营业执照',
            'business_card'=> '名片',
            'document'=> '文字图片'
        );
        $this->view->assign('ocrTypeList', $ocrTypeList);

        return $this->view->fetch();
    }

    /**
     * 前台统一处理
     * @param $ocrType
     * @param $file
     */
    public function ocr()
    {
        $row = $this->request->post('row/a');
        $ocrType = $row['ocrType'];
        $file = $row['image'];

        $upload = \app\common\model\Config::upload();
        if ($cdn = trim($upload['cdnurl'])) {
            $file = $cdn . $file;
        } else {
            $file = ROOT_PATH . 'public' . $file;
        }

        switch ($ocrType)
        {
            case 'id_card-face': //身份证正面
                $this->getIdcard($file, 'face');
                break;
            case 'id_card-back': //身份证背面
                $this->getIdcard($file, 'back');
                break;
            case 'bank_card': //银行卡
                $this->getBankcard($file);
                break;
            case 'vehicle_plate': //车牌号
                $this->getVehicleplate($file);
                break;
            case 'driver_license-face': //驾驶证首页
                $this->getDriverlicense($file, 'face');
                break;
            case 'driver_license-back': //驾驶证副页
                $this->getDriverlicense($file, 'back');
                break;
            case 'business_license': // 营业执照
                $this->getBusinesslicense($file);
                break;
            case 'business_card': //名片
                $this->getBusinesscard($file);
                break;
            case 'document': //文字图片
                $this->getDocument($file);
                break;
            default:
                $this->error('请选择识别类型');
        }
    }

    /**
     * 获取身份证信息
     * @param $file
     * @param $side
     */
    public function getIdcard($file, $side)
    {
        $result = $this->ocr->ocrIdcard($file, $side);
        if ($result === false) {
            $this->error($this->ocr->error);
        }
        $data = $this->ocr->data;
        if ($side === 'face') {
            $info = array(
                ['key'=> 'name', 'cn'=> '姓名', 'value'=> $data['name']],
                ['key'=> 'sex', 'cn'=> '性别', 'value'=> $data['sex']],
                ['key'=> 'nationality', 'cn'=> '民族', 'value'=> $data['nationality']],
                ['key'=> 'birth', 'cn'=> '出生', 'value'=> $data['birth']],
                ['key'=> 'address', 'cn'=> '住址', 'value'=> $data['address']],
                ['key'=> 'num', 'cn'=> '身份证号', 'value'=> $data['num']]
            );
        } else {
            $info = array(
                ['key'=> 'issue', 'cn'=> '签发机关', 'value'=> $data['issue']],
                ['key'=> 'start_date', 'cn'=> '有效期起始时间', 'value'=> $data['start_date']],
                ['key'=> 'end_date', 'cn'=> '有效期结束时间', 'value'=> $data['end_date']]
            );
        }
        $this->success('', '', $info);
    }

    /**
     * 获取银行卡信息
     * @param $file
     */
    public function getBankcard($file)
    {
        $result = $this->ocr->ocrBankcard($file);
        if ($result === false) {
            $this->error($this->ocr->error);
        }
        $data = $this->ocr->data;
        // 目前只能识别卡号
        $info = array(
            ['key'=> 'card_num', 'cn'=> '卡号', 'value'=> $data['card_num']]
        );
        $this->success('', '', $info);
    }

    /**
     * 获取车辆信息
     * @param $file
     */
    public function getVehicleplate($file)
    {
        $result = $this->ocr->ocrVehicleplate($file);
        if ($result === false) {
            $this->error($this->ocr->error);
        }
        $data = $this->ocr->data;
        $info = array();
        foreach ($data['plates'] as $index => $plate) {
            array_push($info, ['key'=> $index, 'cn'=> $plate['txt'], 'value'=> $plate['cls_name']]);
        }
        $this->success('', '', $info);
    }

    /**
     * 获取驾驶证信息
     * @param $file
     * @param string $side
     */
    public function getDriverlicense($file, $side = 'face')
    {
        $result = $this->ocr->ocrDriverlicense($file, $side);
        if ($result === false) {
            $this->error($this->ocr->error);
        }
        $data = $this->ocr->data;
        if ($side === 'face') {
            $info = array(
                ['key'=> 'name', 'cn'=> '姓名', 'value'=> $data['name']],
                ['key'=> 'num', 'cn'=> '驾驶证号', 'value'=> $data['num']],
                ['key'=> 'vehicle_type', 'cn'=> '准驾车型', 'value'=> $data['vehicle_type']],
                ['key'=> 'start_date', 'cn'=> '有效期起始时间', 'value'=> $data['start_date']],
                ['key'=> 'end_date', 'cn'=> '有效期结束时间或时长', 'value'=> $data['end_date']],
                ['key'=> 'issue_date', 'cn'=> '初次领证时间', 'value'=> $data['issue_date']],
                ['key'=> 'addr', 'cn'=> '地址', 'value'=> $data['addr']],
                ['key'=> 'sex', 'cn'=> '性别', 'value'=> $data['sex']]
            );
        } else {
            $info = array(
                ['key'=> 'archive_no', 'cn'=> '档案编号', 'value'=> $data['archive_no']]
            );
        }
        $this->success('', '', $info);
    }

    /**
     * 获取营业执照信息
     * @param $file
     */
    public function getBusinesslicense($file)
    {
        $result = $this->ocr->ocrBusinesslicense($file);
        if ($result === false) {
            $this->error($this->ocr->error);
        }
        $data = $this->ocr->data;
        $info = array(
            ['key'=> 'reg_num', 'cn'=> '注册号', 'value'=> $data['reg_num']],
            ['key'=> 'name', 'cn'=> '公司名称', 'value'=> $data['name']],
            ['key'=> 'type', 'cn'=> '公司类型', 'value'=> $data['type']],
            ['key'=> 'person', 'cn'=> '公司法人', 'value'=> $data['person']],
            ['key'=> 'establish_date', 'cn'=> '注册日期', 'value'=> $data['establish_date']],
            ['key'=> 'valid_period', 'cn'=> '终止日期(20991231代表长期)', 'value'=> $data['valid_period']],
            ['key'=> 'address', 'cn'=> '公司地址', 'value'=> $data['address']],
            ['key'=> 'capital', 'cn'=> '注册资本', 'value'=> $data['capital']],
            ['key'=> 'business', 'cn'=> '经营范围', 'value'=> $data['business']]
        );
        $this->success('', '', $info);
    }

    /**
     * 获取名片信息
     * @param $file
     */
    public function getBusinesscard($file)
    {
        $result = $this->ocr->ocrBusinesscard($file);
        if ($result === false) {
            $this->error($this->ocr->error);
        }
        $data = $this->ocr->data;
        $info = array(
            ['key'=> 'name', 'cn'=> '姓名', 'value'=> $data['name']],
            ['key'=> 'company', 'cn'=> '公司', 'value'=> implode('，', $data['company'])],
            ['key'=> 'department', 'cn'=> '部门', 'value'=> implode('，', $data['department'])],
            ['key'=> 'title', 'cn'=> '职位', 'value'=> implode('，', $data['title'])],
            ['key'=> 'tel_cell', 'cn'=> '手机', 'value'=> implode('，', $data['tel_cell'])],
            ['key'=> 'tel_work', 'cn'=> '座机', 'value'=> implode('，', $data['tel_work'])],
            ['key'=> 'addr', 'cn'=> '地址', 'value'=> implode('，', $data['addr'])],
            ['key'=> 'email', 'cn'=> '邮箱', 'value'=> implode('，', $data['email'])]
        );
        $this->success('', '', $info);
    }

    /**
     * 获取文字图片的文字
     * @param $file
     */
    public function getDocument($file)
    {
        $result = $this->ocr->ocrDocument($file);
        if ($result === false) {
            $this->error($this->ocr->error);
        }
        $data = $this->ocr->data;
        $info = array();
        foreach ($data['words'] as $index => $word) {
            array_push($info, ['key'=> $index, 'cn'=> '', 'value'=> $word]);
        }
        $this->success('', '', $info);
    }
}
